package com.dhu.stylefit.controller;

import com.dhu.stylefit.Response;
import com.dhu.stylefit.dao.Clothes;
import com.dhu.stylefit.dto.ClothesDTO;
import com.dhu.stylefit.service.ClothesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

import static com.dhu.stylefit.converter.ClothesConverter.convertClothes;

@RestController
@RequestMapping("/api/clothes")
public class ClothesUploadController {

    @Value("${file.upload-dir}")
    private String uploadDir;

    @Value("${file.access-path}")
    private String accessPath;

    @Autowired
    private ClothesService clothesService;

    private static final List<String> ALLOWED_TYPES = Arrays.asList("image/jpeg", "image/png");
    private static final long MAX_FILE_SIZE = 10 * 1024 * 1024;

    // 添加服装
    @PostMapping("/upload")
    public Response<ClothesDTO> uploadClothes(
            @RequestParam String name,
            @RequestParam String description,
            @RequestParam Long categoryId,
            @RequestParam Long userId,
            @RequestParam MultipartFile image) {

        try {
            // 1. 验证文件
            if (image.isEmpty()) {
                return Response.newFail("请选择要上传的图片");
            }

            // 2. 验证文件类型
            String contentType = image.getContentType();
            if (contentType == null || !ALLOWED_TYPES.contains(contentType)) {
                return Response.newFail("只支持 JPG/PNG 格式的图片");
            }

            // 3. 验证文件大小
            if (image.getSize() > MAX_FILE_SIZE) {
                return Response.newFail("图片大小不能超过 10MB");
            }

            // 4. 获取项目根目录
            String projectRoot = System.getProperty("user.dir");
            Path uploadPath = Paths.get(projectRoot, uploadDir).toAbsolutePath().normalize();

            // 5. 确保目录存在
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 6. 生成唯一文件名
            String originalFilename = image.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String uniqueFilename = UUID.randomUUID().toString() + fileExtension;

            // 7. 保存文件
            Path filePath = uploadPath.resolve(uniqueFilename);
            Files.copy(image.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

            // 8. 创建衣物实体
            Clothes clothes = new Clothes();
            clothes.setName(name);
            clothes.setDescription(description);
            clothes.setCategory(categoryId);
            clothes.setUserId(userId);
            clothes.setImageUrl(accessPath + uniqueFilename);
            clothes.setCreatedAt(Timestamp.from(Instant.now()));

            // 9. 保存到数据库
            Clothes savedClothes = clothesService.saveClothes(clothes);
            ClothesDTO clothesDTO = convertClothes(savedClothes);

            return Response.newSuccess(clothesDTO);

        } catch (Exception e) {
            e.printStackTrace();
            return Response.newFail("文件上传失败: " + e.getMessage());
        }
    }

    // 更新服装
    @PutMapping("/upload/{id}")
    public Response<ClothesDTO> updateClothes(
            @PathVariable Long id,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String description,
            @RequestParam(required = false) Long categoryId,
            @RequestParam(required = false) MultipartFile image) {

        try {
            // 1. 获取现有服装信息
            ClothesDTO existingClothes = clothesService.getClothesById(id);
            if (existingClothes == null) {
                return Response.newFail("服装不存在");
            }

            // 2. 更新基本信息
            if (name != null) {
                existingClothes.setName(name);
            }
            if (description != null) {
                existingClothes.setDescription(description);
            }
            if (categoryId != null) {
                existingClothes.setCategoryId(categoryId);
            }

            // 3. 处理图片更新
            if (image != null && !image.isEmpty()) {
                // 验证文件类型
                String contentType = image.getContentType();
                if (contentType == null || !ALLOWED_TYPES.contains(contentType)) {
                    return Response.newFail("只支持 JPG/PNG 格式的图片");
                }

                // 验证文件大小
                if (image.getSize() > MAX_FILE_SIZE) {
                    return Response.newFail("图片大小不能超过 10MB");
                }

                // 获取上传路径
                String projectRoot = System.getProperty("user.dir");
                Path uploadPath = Paths.get(projectRoot, uploadDir).toAbsolutePath().normalize();

                // 确保目录存在
                if (!Files.exists(uploadPath)) {
                    Files.createDirectories(uploadPath);
                }

                // 生成唯一文件名
                String originalFilename = image.getOriginalFilename();
                String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
                String uniqueFilename = UUID.randomUUID().toString() + fileExtension;

                // 保存新文件
                Path filePath = uploadPath.resolve(uniqueFilename);
                Files.copy(image.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

                // 删除旧图片
                if (existingClothes.getImageUrl() != null) {
                    String oldFilename = existingClothes.getImageUrl().replace(accessPath, "");
                    Path oldFilePath = uploadPath.resolve(oldFilename);
                    Files.deleteIfExists(oldFilePath);
                }

                // 更新图片URL
                existingClothes.setImageUrl(accessPath + uniqueFilename);
            }

            // 4. 保存到数据库
            ClothesDTO updatedClothes = clothesService.updateClothes(existingClothes);

            return Response.newSuccess(updatedClothes);

        } catch (Exception e) {
            e.printStackTrace();
            return Response.newFail("服装更新失败: " + e.getMessage());
        }
    }

}
